import { FieldConfig } from '@/types';
import traverse from 'traverse';

export function fieldConfig2TreeData(fieldConfig: FieldConfig) {
  // console.log(fieldConfig);
  return traverse(fieldConfig).reduce(
    function (acc) {
      const { path, key, isRoot, isLeaf } = this;

      if (isRoot) {
        return acc;
      }
      // console.log(path, key);
      const treeDataItem = createTreeDataItem({
        path,
        key: key as string,
        isLeaf,
      });
      if (path.length === 1) {
        acc.treeData.push(treeDataItem);
      } else {
        acc.treeDataItemStack.at(-1).children.push(treeDataItem);
      }
      if (!isLeaf) {
        acc.treeDataItemStack.push(treeDataItem);
        this.after(function () {
          // console.log('after', path, key);
          acc.treeDataItemStack.pop();
        });
      }

      return acc;
    },
    { treeData: [], treeDataItemStack: [] },
  ).treeData;
}
function createTreeDataItem({
  path,
  key,
  isLeaf,
}: {
  path: string[];
  key: string;
  isLeaf: boolean;
}) {
  const pathStr = path.join('/');
  if (isLeaf) {
    return {
      title: key,
      key: pathStr,
    };
  } else {
    return {
      title: key,
      key: pathStr,
      children: [],
    };
  }
}
